package jlb.andriva;

import jlb.andriva.wrappers.HttpTask;
import jlb.andriva.wrappers.Settings;
import jlb.andriva.wrappers.Util;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.Activity;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import jlb.andriva.R;

/**
 * Activity which displays a login screen to the user.
 */
public class LoginActivity extends Activity {
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
	public static boolean mTestMode = false;
    private UserLoginTask mAuthTask = null;

    private Settings mSet;
    // Values for email and password at the time of the login attempt.
    private String mUser;
    private String mPassword;
    private LoginActivity mActivity = this;

    // UI references.
    private EditText mUserView;
    private EditText mPasswordView;
    private Button mLoginButton;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    private CheckBox mCheckMode;

    public static DefaultHttpClient webClient;// = new DefaultHttpClient();
    
    private BroadcastReceiver mReceiver;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2) {
	        BasicHttpParams params = new BasicHttpParams();
	        SchemeRegistry schemeRegistry = new SchemeRegistry();
	        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
	        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
	        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
	        webClient = new DefaultHttpClient(cm, params);
        }
        else{
        	webClient = new DefaultHttpClient();
        }
        
        mTestMode = ((CheckBox)mActivity.findViewById(R.id.login_checkmode)).isChecked();

        setUIReferences();
        setUIListeners();

        if(mTestMode == false){
	        mReceiver = new NetworkStateReceiver();
	        registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }

        mSet = new Settings(this);
        mSet.loadSettings();
        if(!TextUtils.isEmpty(mSet.user)){
            mUserView.setText(mSet.user);
            mPasswordView.requestFocus();
        }
    }
    
    @Override
    public void onDestroy(){
    	try{
    		unregisterReceiver(mReceiver);
    	}
    	catch(Exception ex){
    	}
    	super.onDestroy();
    }

    private void setUIReferences(){
        mUserView = (EditText) findViewById(R.id.login_user);
        mPasswordView = (EditText) findViewById(R.id.login_password);
        mLoginButton = (Button) findViewById(R.id.login_sign_in_button);
        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
        mCheckMode = (CheckBox) findViewById(R.id.login_checkmode);
    }

    private void setUIListeners(){
    	mCheckMode.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton checkView, boolean isChecked) {
				mTestMode = isChecked;
				if(mTestMode == false){
					registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
				}
				else{
					unregisterReceiver(mReceiver);
					ChangeConnectionState(true);
				}
			}
    		
    	});
    	
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_ACTION_DONE) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    private void ChangeConnectionState(boolean IsConnected){
        LinearLayout errorll = (LinearLayout) findViewById(R.id.login_error);
        LayoutParams params = errorll.getLayoutParams();
        if(IsConnected){
            params.height = 0;
            errorll.removeAllViews();

            ((Button) findViewById(R.id.login_sign_in_button)).setEnabled(true);
        }
        else{
            errorll.setBackgroundResource(R.drawable.infolayout);
            params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            params.width = LinearLayout.LayoutParams.FILL_PARENT;

            TextView txt = new TextView(this);
            txt.setGravity(Gravity.CENTER);
            txt.setEllipsize(TextUtils.TruncateAt.END);
            txt.setTextColor(Color.WHITE);
            txt.setLayoutParams(params);
            txt.setText("Red no disponible");

            errorll.addView(txt);

            mUserView.setError(null);
            mPasswordView.setError(null);

            ((Button) findViewById(R.id.login_sign_in_button)).setEnabled(false);
        }
    }

    private class NetworkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ChangeConnectionState(isNetworkAvailable());
        }
    }

    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        
        InputMethodManager inputMethodManager = (InputMethodManager)  this.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);

        // Reset errors.
        ShowError("");
        mUserView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mUser = mUserView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < 4) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid user.
        if (TextUtils.isEmpty(mUser)) {
            mUserView.setError(getString(R.string.error_field_required));
            focusView = mUserView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            /*if(TextUtils.isEmpty(mSet.user)){
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Desea guardar el usuario y la contrasena?").setPositiveButton("Si", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();
            }*/
            //SAVE CREDENTIALS
            mSet.user = mUser;
            mSet.saveSettings();

            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            if(mTestMode == false){
	            mAuthTask = new UserLoginTask();
	            mAuthTask.execute(getString(R.string.login_url), "username", mUser, "password", mPassword);
            }
            else{
            	showProgress(false);
            	
            	if(mPassword.equals("password")){
            		Intent change = null;
	                Configuration config = getResources().getConfiguration();
	                /*if (config.smallestScreenWidthDp < 600) {
	                	change = new Intent(mActivity, PassActivity.class);
	                }
	                else{*/
	                	change = new Intent(mActivity, PassActivity.class);
	                //}
	                
	                change.putExtra("username", mUser);
	                change.putExtra("data", Util.getRawContent(mActivity, R.raw.change));
	                startActivity(change);
            	}
            	else{
	            	Intent pager = null;
	                Configuration config = getResources().getConfiguration();
	                /*if (config.smallestScreenWidthDp < 600) {
	                    pager = new Intent(mActivity, PagerActivity.class);
	                }
	                else{*/
	                    pager = new Intent(mActivity, PagerActivity.class);
	                //}
	                
	                pager.putExtra("data", Util.getRawContent(mActivity, R.raw.welcome));
	                startActivity(pager);
            	}
            }
        }
    }

    /*DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    mSet.user = mUser;
                    mSet.saveSettings();
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //No button clicked
                    break;
            }
        }
    };*/

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private class UserLoginTask extends HttpTask {
        @Override
        protected void onPostExecute(final String result) {
            mAuthTask = null;
            showProgress(false);

            if (result != null) {
                if(!result.startsWith("ERROR")){
                    Document doc = org.jsoup.Jsoup.parse(result);
                    Element table = doc.select("#plasticId").first();
                    if(table != null){
                        Intent pager = null;
                        Configuration config = getResources().getConfiguration();
/*                        if (config.smallestScreenWidthDp < 600) {
                            pager = new Intent(mActivity, PagerActivity.class);
                        }
                        else{*/
                            pager = new Intent(mActivity, PagerActivity.class);
//                        }
                        pager.putExtra("data", result);
                        startActivity(pager);
                    }
                    else{
                    	Element form = doc.select("#changePassword_send").first();
                        if(form != null){
                        	Intent change = null;
                            Configuration config = getResources().getConfiguration();
                            if (config.smallestScreenWidthDp < 600) {
                                change = new Intent(mActivity, PassActivity.class);
                            }
                            else{
                                change = new Intent(mActivity, PassActivity.class);
                            }
                            change.putExtra("data", result);
                            change.putExtra("username", mUser);
                            startActivity(change);
                        }
                        else{
                        	mPasswordView.setError(getString(R.string.error_incorrect_password));
                            mPasswordView.requestFocus();
                        }
                    }
                }
                else{
                    ShowError(result);
                }

            } else {
                ShowError("ERROR: No se pudieron obtener los datos.");
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    private void ShowError(String errorMsg){
        LinearLayout errorll = (LinearLayout) findViewById(R.id.login_error);
        LayoutParams params = errorll.getLayoutParams();
        if(!TextUtils.isEmpty(errorMsg)){
            errorll.setBackgroundResource(R.drawable.errorlayout);
            params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            params.width = LinearLayout.LayoutParams.FILL_PARENT;

            TextView txt = new TextView(this);
            txt.setGravity(Gravity.CENTER);
            txt.setEllipsize(TextUtils.TruncateAt.END);
            txt.setTextColor(Color.WHITE);
            txt.setLayoutParams(params);
            txt.setText(errorMsg);

            errorll.addView(txt);

            mUserView.setError(null);
            mPasswordView.setError(null);
        }
        else{
            params.height = 0;
            errorll.removeAllViews();
        }
    }
}